package com.hnphqs.nemoapi.CloudV;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hnphqs.nemoapi.CloudV.listV;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.Response;

import java.io.IOException;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class listV {

    public void 大牛大牛求你别逆向了(){}
    public void 我这代码写的像坨屎不要吃屎了(){}

    private static final String URL = "wss://socketcv.codemao.cn:9096/cloudstorage/?session_id=<work_id>&authorization_type=2&stag=2&token=Bearer%20<token>&EIO=3&transport=websocket";
    private final OkHttpClient client = new OkHttpClient();
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private WebSocket webSocket;
    
    
    public void connect(String workId, String token, String cloudVName,View editCVID,Context context) {
        String urlWithParameters = URL.replace("<work_id>", workId).replace("<token>", token);
        System.out.println(urlWithParameters);
        Request request = new Request.Builder()
                .url(urlWithParameters)
                .build();
        // 保存 WebSocket 的引用
        webSocket=client.newWebSocket(request, new WebSocketListener(cloudVName,context,editCVID));
    }

    private class WebSocketListener extends okhttp3.WebSocketListener {
        private final String cloudVName;
        private final Context context;
        private final View editCVID;
        
        public WebSocketListener(String cloudVName,Context context,View editCVID) {
            this.cloudVName = cloudVName;
            this.context=context;
            this.editCVID=editCVID;
        }

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            System.out.println("WebSocket connection opened!");
            // 发送 join 消息
            webSocket.send("42[\"join\",\"\"]");
            // 发送 list_variables 消息
            webSocket.send("42[\"list_variables\",{}]");
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            System.out.println("Received message: " + text);
            parseResponse(text, cloudVName,editCVID,context);
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            System.out.println("WebSocket closed with code: " + code + " and reason: " + reason);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            System.out.println("WebSocket failure: " + t.getMessage());
            mHandler.post(new Runnable() {
                @Override
                    public void run() {
                        Toast.makeText(context,"查询失败："+t.getMessage(),Toast.LENGTH_LONG).show();
                    }
            });
        }

        private void parseResponse(String text, String cloudVName,View editCVID, Context context) {
            try {
                // 分割消息以提取实际的 JSON 数据
                String[] parts = text.split(",\"");
                if (parts.length >= 2) {
                    String code = parts[0];
                    if ("42[\"list_variables_done\"".equals(code)) {
                        String listVStr = text.substring(2);
                        System.out.println("Variables JSON: " + listVStr);
                        List list = parseJsonToList(listVStr);
                        Map<String, Object> dict = toDict(list, cloudVName);
                        System.out.println(dict);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(context,"查询成功!",Toast.LENGTH_LONG).show();
                                new AlertDialog.Builder(context)
                                .setTitle("查询结果")
                                .setMessage(buildDictionaryMessage(dict))
                                .setPositiveButton("确定", null)
                                .create()
                                .show();
                                String cvid=(String)dict.get("cvid");  
                                EditText edit=(EditText)editCVID;
                                edit.setText(cvid);
                            }
                        });
                        closeWebSocket();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static List<String> parseJsonToList(String jsonString) {
        Gson gson = new Gson();
        Type typeOfList = new TypeToken<List<String>>(){}.getType();
        List<String> resultList = gson.fromJson(jsonString, typeOfList);
        return resultList;
    }

    public static Map<String, Object> toDict(List<String> list, String nameToFind) {
        Gson gson = new Gson();
        Type typeOfList = new TypeToken<List<Map<String, Object>>>(){}.getType();
        List<Map<String, Object>> dictionaries = gson.fromJson(list.get(1), typeOfList);
        for (Map<String, Object> dictionary : dictionaries) {
            if (dictionary.get("name").equals(nameToFind)) {
                return dictionary;
            }
        }
        return null;
    }
    
    private static String buildDictionaryMessage(Map<String, Object> dictionary) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : dictionary.entrySet()) {
            sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
        }
        return sb.toString();
    }
    
    private void closeWebSocket() {
        if (webSocket != null) {
            webSocket.close(1000, "Closing the connection manually.");
        }
    }
}